/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.partaljevic.tapestry.gambling.pages;

import com.partaljevic.gambling.beans.CustomerBean;
import com.partaljevic.gambling.Customer;
import com.partaljevic.gambling.Identifiable;
import com.partaljevic.tapestry.gambling.service.Customers;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 *
 * @author Danilo
 */
public class Register {

    @Property
    @Persist
    private Customer customer;
    @Property
    @Persist("flash")
    private String message;
    @Inject
    private Customers customers;
    @InjectPage
    private Welcome welcome;
    private long ID;

    public long getID(){
        return ID;
    }

    @SetupRender
    void createObject(){
        customer = new CustomerBean();
    }
    Object onSubmitFromRegisterForm() {
        if (!existCustomer()) {
            ID = Identifiable.class.cast(customers.save(customer)).getID();
            welcome.setID(ID);
            System.out.println("U bazi ima korinsika " + customer);
            return welcome;
        }
        return null;
    }

    boolean existCustomer() {
        for (Customer cust : customers.retrieve()) {
            if (cust.getUsername().equals(customer.getUsername())) {
                message = "Customer with username: "+customer.getUsername()+" exist! Try new one!";
                return true;
            }
        }
        return false;
    }
}
